<?php

namespace Syrius\Query;

/**
 * Enter description here ...
 * @package	Query
 * @author	Domenico Biancardi <domenico.biancardi@gmail.com>
 * @link	http://code.google.com/p/syrius/
 *
 */ class Select extends Query {
	private $_opts;

	private $_selectExpr;

	private $_tableReferences;

	private $_groupBy;

	private $_havingCondition;


	public function __construct($model) {
        $this -> _model = $model;
		$this->_tableReferences [] = $model->source();
		$fields = $model->fields();
		if (count($fields) == 0)
			$this->_selectExpr [] = "*"; else {
			foreach ($fields as $k => $v) {
				if (!$v instanceof \Syrius\Type\Relation_Many_To_Many) {
					$this->_selectExpr [] = $k;
				}
			}
		}
	}

	public function __toString() {
		$sql = "SELECT " . implode(",", $this->_selectExpr) . " FROM " . implode(",", $this->_tableReferences);

		if (count($this->_whereConditions) > 0) {
			$sql .= " WHERE ";
		}
		for ($i = 0; $i < count($this->_whereConditions); $i++) {
			if (is_array($this->_whereConditions [$i])) {

				$k = array_keys($this->_whereConditions [$i]);
				$v = array_values($this->_whereConditions [$i]);
				$k = $k [0];
				$v = $v [0];
				if ($v instanceOf \Syrius\Model\Entity) {
					$primaryKey = $v->getModel()->getPrimaryKey();
					$primaryKey = $primaryKey->getName();
					$sql .= " $k = " . $v->$primaryKey[0];

				} else {
					$sql .= " $k = $v";
				}

			} else {
				$sql .= " " . $this->_whereConditions [$i];
			}
		}
		if (count($this->_orderBy) > 0) {
			$sql .= " ORDER BY ";
		}
		for ($i = 0; $i < count($this->_orderBy); $i++) {
			if (is_array($this->_orderBy [$i])) {
				$k = array_keys($this->_orderBy [$i]);
				$v = array_values($this->_orderBy [$i]);
				$k = $k [0];
				$v = $v [0];
				$sql .= " $k $v";
			} else {
				$sql .= " " . $this->_orderBy [$i];
			}
		}
        if (isset($this -> _limit["start"])){
            $sql .= " LIMIT " . $this -> _limit["start"] . "," . $this -> _limit["length"];
        }
		return $sql;
	}

	public function fields($field) {
		if (is_array($field)) {
			for ($i = 0; $i < count($field); $i++) {
				$this->_selectExpr [] = $field [$i];
			}
		} else {
			$this->_selectExpr [] = $field;
		}

		return $this;
	}

	public function removeField($field) {
		$index = array_search($field, $this->_selectExpr);
		unset ($this->_selectExpr [$index]);
		return $this;
	}

}

?>
